<?php

class Child_Model 
{
    protected $_dbTable;
    protected $_row;
    
    public  function __construct(Zend_Db_Table_Abstract $dbTable, $id, $fieldName, $field) 
    {
        $this->_dbTable = $dbTable;
        if($id){
            $this->_row = $this->_dbTable->find($id)->current();
        } elseif(isset($field) && isset($fieldName)) {
            $select = $this->_dbTable->select();
            $select->where($fieldName .' = ?', $field);
            $this->_row = $this->_dbTable->fetchAll($select)->current();
        } else {
            $this->_row = $this->_dbTable->createRow();
        }
    }
    

    public function fill($data) {
        foreach($data as $key => $value){
            if(isset($this->_row->$key)){
                $this->_row->$key = $value;
            }
        }
    }
    
    public function getAll(){
    
        return $this->_dbTable->fetchAll();
    }
    
    public function select($fieldName, $field){
        $select = $this->_dbTable->select();
            $select->where($fieldName .' = ?', $field);
            $this->_row = $this->_dbTable->fetchAll($select)->current();
    }
    
    public function populateForm(){
        return $this->_row->toArray();
    }
    
    public function delete(){
        $this->_row->delete();
    }

    public function save()
    {
        $this->_row->save();
    }

    public function __set($name, $value) {
        if(isset($this->_row->$name)){
            $this->_row->$name = $value;
        }
    }
    
    public function __get($name) {
        if(isset($this->_row->$name)){
            return $this->_row->$name;
        }
    }
}
